package org.example.likou150.tree;


// https://leetcode.cn/problems/sum-root-to-leaf-numbers/?envType=study-plan-v2&envId=top-interview-150
public class SumNumbers {

    public static void main(String[] args) {
        TreeNode root = new TreeNode(1);
//        root.left = new TreeNode(2);
        root.right = new TreeNode(3);

        SumNumbers s = new SumNumbers();
        System.out.println(s.sumNumbers(root));;
    }

    public int sumNumbers(TreeNode root) {
        return sum(root, 0);
    }

    private int sum(TreeNode root, int val){
        if(root==null){
            return 0;
        }
        val = val*10 + root.val;
        if(root.left==null && root.right==null){
            return val;
        }
        return sum(root.right, val) + sum(root.left, val);
    }


     public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode() {}
        TreeNode(int val) { this.val = val; }
        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}
